<?php

namespace Beerus\Modules\GoodsTest\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\bigData\UserConsumeDecisionScore;
use Biz\model\GoodsTestActivity\FineGoodsJoinModel;
use Biz\model\GoodsTestActivity\FineGoodsJoinRecordModel;
use Biz\model\GoodsTestActivity\FineGoodsModel;
use Biz\pockets\excel\DownExcel;
use Biz\service\GoodsTestActivity\BigDataService;
use Biz\service\GoodsTestActivity\FineGoodsService;
use Doraemon\service\User;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\Phone as PhoneModel;
use hhz\constant\basic\UserExtendPhoneScene;

class JoinController extends Controller
{
    const PAGE_SIZE = 20;

    public function joinList(Request $request, Content $content, $id)
    {
        Admin::script($this->joinScript());
        $fans = $request->input('fans', '');
        $search = $request->input('search', '');
        $fans = (strlen($fans) > 0) ? $fans : null;
        $search = (strlen($search) > 0) ? $search : null;
        $page = $request->input('page', 1);
        if (is_null($search) && is_null($fans)) {
            $request->merge([
                'search' => 0,
            ]);
            $search = 0;
        }

        $fineGoodsInfo = FineGoodsModel::first(['id' => $id]);
        if ($fineGoodsInfo) {
            $joinResult = [];
            //获取组合套餐数据
            $package = FineGoodsModel::PACKAGE_A;
            if($fineGoodsInfo['type'] < FineGoodsModel::TYPE_EVALUATION) {
                $packageCombinationArr = array_column(json_decode($fineGoodsInfo['package_combination'], true),
                    'package');
                $package = max($packageCombinationArr);
            }
            $confirmNum = FineGoodsJoinModel::getConfirmedNum($id);
            $limit = [($page - 1) * self::PAGE_SIZE, self::PAGE_SIZE];
            $where = [
                'fine_goods_id' => $id,
                'LIMIT' => $limit,
                'ORDER' => ['fans_num' => 'DESC'],
            ];
            if (!is_null($fans)) {
                $where['fans_num_grade'] = $fans;
            } else {
                if (!is_null($search)) {
                    if ($search == 1) {
                        $where['fans_num_grade'] = array_keys(FineGoodsModel::PACKAGE_FANS_GRADE_DATA[$package]);
                    } else {
                        if ($search == 2) {
                            $joinResult = FineGoodsJoinModel::select('*', [
                                'fine_goods_id' => $id,
                                'join_status' => [
                                    FineGoodsJoinModel::JOIN_STATUS_NOT_PREFER,
                                    FineGoodsJoinModel::JOIN_STATUS_PREFER,
                                ],
                                'LIMIT' => $limit,
                            ]);
                            if (!empty($joinResult)) {
                                $where['id'] = array_column($joinResult, 'record_id');
                            } else {
                                $where = null;
                            }
                        }
                    }
                }
            }
            $list = [];
            $total = 0;
            if (!is_null($where)) {
                $list = FineGoodsJoinRecordModel::select('*', $where);
                unset($where['LIMIT']);
                unset($where['ORDER']);
                $total = FineGoodsJoinRecordModel::count($where);
            }
            if($where){
                $search_params = http_build_query($where);
            }else{
                $search_params = [];
            }
            $list = $this->formatData($list,$fineGoodsInfo,$joinResult);
            $result = ['list' => $list, 'total' => $total];
            $gridModel = new pGridDataModel($result['list'], $result['total'], [
                'perPage' => self::PAGE_SIZE,
            ]);
            $fansFilter = FineGoodsModel::PACKAGE_FANS_GRADE_DATA[$package];
            $gridList = Admin::grid($gridModel,
                function (Grid $grid) use ($gridModel, $fansFilter, $fineGoodsInfo, $confirmNum,$search_params) {
                    if($fineGoodsInfo['type'] < FineGoodsModel::TYPE_EVALUATION) {
                        $grid->header(function () use ($fineGoodsInfo, $confirmNum) {
                            $html = "<div style='font-size: 20px'>";
                            $html .= '套餐:<sapn style="font-weight: bold">「'.$fineGoodsInfo['package_combination_name'].'」</sapn>&emsp;';
                            $html .= '当前状态:<sapn style="font-weight: bold">「'.FineGoodsModel::ACTIVITY_STATE[$fineGoodsInfo['activity_state']].'」</sapn>&emsp;';
                            $html .= "本期评测数量:<span style='font-weight: bold;font-size: 35px;'>".$fineGoodsInfo['goods_num']."</span>人&emsp;";
                            $html .= "已有首选人数:<span style='font-weight: bold;font-size: 35px;'>".$confirmNum."</span>人";
                            $html .= "</div>";

                            return $html;
                        });
                    }
                    $grid->setTitle('【粉丝】和【查看】筛选不可叠加使用');
                    $grid->paginate($gridModel->getPerPage());
                    $grid->disableExport();
                    $grid->disableRowSelector();
                    $grid->disableCreateButton();
                    $grid->filter(function (Grid\Filter $filter) use ($fansFilter,$fineGoodsInfo) {
                        $filter->disableIdFilter();
                        $filter->column(1 / 2, function ($filter) use ($fansFilter) {
                            $filter->equal('fans', '粉丝')->select($fansFilter);
                        });
                        $filter->column(1 / 2, function (Grid\Filter $filter) use($fineGoodsInfo) {
                            $selectOption = [0 => '所有申请', 1 => '符合要求', 2 => '已选用户'];
                            if($fineGoodsInfo['type'] >= FineGoodsModel::TYPE_EVALUATION){
                                unset($selectOption[1]);
                            }
                            $filter->equal('search', '查看')->select($selectOption);
                        });
                        $filter->expand();
                    });
                    // 添加导出按钮
                    $grid->tools(function (Grid\Tools $tool) use ($grid, $search_params) {
                        $url = url('/admin/goodsTest/join/exportList?'. $search_params);
                        $button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出测评名单</span></a>
                    </div>';
                        $tool->append($button);
                    });
                    $grid->column("id", 'id');
                    $grid->column('uid', '用户uid');
                    $grid->column('nick', '用户昵称')->modal('收货地址', function () {
                        $html = '<ul class="list-unstyled">';
                        $html .= '<li>uid&emsp;&emsp;&emsp;&emsp;&nbsp;&nbsp;&nbsp;' . $this->uid . '</li>';
                        $html .= '<li>昵称&emsp;&emsp;&emsp;&emsp;' . $this->nick . '</li>';
                        $html .= '<li>姓名&emsp;&emsp;&emsp;&emsp;' . $this->name . '</li>';
                        $html .= '<li>手机号码&emsp;&emsp;' . $this->phone . '</li>';
                        $html .= '<li>地址&emsp;&emsp;&emsp;&emsp;' . $this->address . '</li>';
                        $html .= '</ul>';

                        return $html;
                    });
                    $grid->column('history_title', '历史获选')->display(function () {
                        $html = '';
                        if ($this->history_title) {
                            foreach ($this->history_title as $row) {
                                $html .= '<ul class="list-unstyled">';
                                $html .= '<li>' . $row . '</li>';
                                $html .= '</ul>';
                            }
                        }
                        return $html;
                    });
                    $grid->column('tag_list', '用户标签');
                    $grid->column('fans_num', '粉丝数');
                    $grid->column('brand_id', '近一年决策影响力指数')->display(function () {
                        $html = '<ul class="list-unstyled">';
                        $html .= "<li><span class='label label-info'>" . UserConsumeDecisionScore::PRODUCT_SCORE . ':' . $this->score[0]['score'] . "</span></li>";
                        $html .= "<li><span class='label label-success'>" . UserConsumeDecisionScore::WIKI_SCORE . ':' . $this->score[1]['score'] . "</span></li>";
                        $html .= "<li><span class='label label-warning'>" . UserConsumeDecisionScore::CREDIT_SCORE . ':' . $this->score[2]['score'] . "</span></li>";
                        $html .= '</ul>';

                        return $html;
                    })->width(120);
                    $grid->column('logistics_status', '是否发货')->display(function () {
                        if ($this->join_status == FineGoodsJoinModel::JOIN_STATUS_PREFER) {
                            return isset(FineGoodsJoinModel::LOGISTICS_STATUS_MAP[$this->logistics_status]) ? FineGoodsJoinModel::LOGISTICS_STATUS_MAP[$this->logistics_status] : '';
                        }
                    });
                    $grid->column("join_status", '状态')->display(function () {
                        return FineGoodsJoinModel::JOIN_STATUS_DESC[$this->join_status];
                    })->label([
                        0 => 'default',
                        1 => 'warning',
                        2 => 'success',
                        9 => 'danger',
                    ]);
                    $grid->actions(function (Grid\Displayers\Actions $actions) {
                        $actions->disableEdit();
                        $actions->disableDelete();
                        //已发货的不允许操作
                        if ($actions->row->logistics_status != FineGoodsJoinModel::LOGISTICS_STATUS_SHIPPED) {
                            if (in_array($actions->row->join_status,
                                [FineGoodsJoinModel::JOIN_STATUS_NOT_PREFER, FineGoodsJoinModel::JOIN_STATUS_PREFER])) {
                                $actions->prepend('&nbsp;&nbsp;<a class="fa operate-state" data-state="' . FineGoodsJoinModel::JOIN_STATUS_DEL . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">取消</a>');
                            }
                            $actions->prepend('&nbsp;&nbsp;<a class="fa operate-state" data-state="' . FineGoodsJoinModel::JOIN_STATUS_NOT_PREFER . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">备选</a>');
                            $actions->prepend('&nbsp;&nbsp;<a class="fa operate-state" data-state="' . FineGoodsJoinModel::JOIN_STATUS_PREFER . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">首选</a>');
                        }
                    });
                }
            );
            $content->row($gridList);
            $header = FineGoodsModel::TYPE_MAP[$fineGoodsInfo['type']].' ｜ ' . $fineGoodsInfo['activity_title'] . ' / 名单管理';

            return $content
                ->header($header)
                ->description('')
                ->breadcrumb([
                    'text' => '审核列表',
                    'url' => url('/admin/goodsTest/index'),
                ], ['text' => '名单管理']);
        } else {
            return $content->row('未查询到活动信息');
        }
    }

    private function joinScript()
    {
        return <<<SCRIPT
        $('.operate-state').unbind('click').click(function(){
            var id= $(this).data('id');
            var state=$(this).data('state');
            let url = '/admin/goodsTest/join/choose';
            let params = {id:id,state:state};
            let title='确定要操作吗？';
            if(state==1){
                title='确定要备选吗？';
            }else if(state==2){
                title='确定要首选吗？';
            }else if(state==9){
                title='确定要取消吗？';
            }
            layer.confirm(title, {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            });
        });
SCRIPT;
    }

    public function chooseJoin(Request $request)
    {
        $id = $request->input('id', 0);
        $state = $request->input('state', 0);
        try {
            if (!$id || !$state) {
                throw new Exception('参数错误');
            }
            $joinRecodeInfo = FineGoodsJoinRecordModel::first(['id' => $id]);
            $joinInfo = FineGoodsJoinModel::first(['record_id' => $id]);
            if (empty($joinRecodeInfo)) {
                throw new Exception('不存在的报名信息');
            }
            $fineGoodsId = $joinRecodeInfo['fine_goods_id'];
            $activityInfo = FineGoodsService::getById($fineGoodsId);
            $goodsNum = $activityInfo['goods_num'];
            $confirmNum = FineGoodsJoinModel::getConfirmedNum($fineGoodsId);
            if (empty($activityInfo)) {
                throw new Exception('不存在的活动');
            }
            $joinData = [
                'fine_goods_id' => $joinRecodeInfo['fine_goods_id'],
                'record_id' => $id,
                'uid' => $joinRecodeInfo['uid'],
            ];
            switch ($state) {
                case FineGoodsJoinModel::JOIN_STATUS_NOT_PREFER://备选
                    $joinData['join_status'] = FineGoodsJoinModel::JOIN_STATUS_NOT_PREFER;
                    break;
                case FineGoodsJoinModel::JOIN_STATUS_PREFER://首选
                    if ($confirmNum >= $goodsNum) {
                        throw new Exception('首选名额已达上限');
                    }
                    $joinData['join_status'] = FineGoodsJoinModel::JOIN_STATUS_PREFER;
                    break;
                case FineGoodsJoinModel::JOIN_STATUS_DEL://取消
                    $joinData['join_status'] = FineGoodsJoinModel::JOIN_STATUS_DEL;
                    break;
                default:
                    throw new Exception('非法操作');
            }
            if (empty($joinInfo)) {
                $result = FineGoodsJoinModel::insertData($joinData);
            } else {
                $result = FineGoodsJoinModel::updateData($joinData, ['id' => $joinInfo['id']]);
            }
            if (!$result) {
                throw new Exception('数据操作错误');
            }
            $success = [
                'title' => '操作成功',
                'code' => 1,
            ];

            return response()->json($success);
        } catch (Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];

            return response()->json($success);
        }
    }

    /**
     * 导出测评名单
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse|void
     */
    public function exportList(Request $request)
    {
        $params = $request->all();
        $where = [];
        if(isset($params['fine_goods_id']) && !empty($params['fine_goods_id'])){
            $where['fine_goods_id'] = $params['fine_goods_id'];
        }
        if(isset($params['id']) && !empty($params['id'])){
            $where['id'] = $params['id'];
        }
        $data = [];
        if($where){
            $data = FineGoodsJoinRecordModel::select('*', $where);
        }
        if (count($data) == 0) {
            $error = new MessageBag([
                'title' => '暂无符合条件订单数据可导出'
            ]);
            return back()->with(compact('error'));
        }
        $fineGoodsInfo = FineGoodsModel::first(['id' => $params['fine_goods_id']]);
        $data = $this->formatData($data,$fineGoodsInfo);

        $lists = [];
        foreach ($data as $item) {
            if($item){
                $history_title = implode(',',$item['history_title']);
            }else{
                $history_title = '';
            }
            $lists[] = [
                'uid' => $item['uid'],
                'nick' => $item['nick'],
                'history_title' => $history_title,
                'tag_list' => $item['tag_list'],
                'fans_num' => $item['fans_num'],
                'score' => UserConsumeDecisionScore::PRODUCT_SCORE . ':' . $item['score'][0]['score'].','.UserConsumeDecisionScore::WIKI_SCORE . ':' . $item['score'][1]['score'].','.UserConsumeDecisionScore::CREDIT_SCORE . ':' . $item['score'][2]['score'],
            ];
        }
        $header = [
            '用户UID','用户昵称','历史获选','用户标签','粉丝数','近一年决策影响力指数'
        ];
        $excel_obj = new DownExcel();
        $excel_obj->setFileName($fineGoodsInfo['activity_title'].'-测评名单 - ' . date('YmdHis'));
        $excel_obj->setSheetTitle($fineGoodsInfo['activity_title'].'-测评名单');

        // 设置列宽
        $widths = [
            'A' => 15,
            'B' => 15,
            'C' => 30,
            'D' => 30,
            'E' => 15,
            'F' => 40,
        ];

        $excel_obj->setWidth($widths);
        $excel_obj->setDefaultStyleAlignment();
        $excel_obj->setTextFormat('A');
        $excel_obj->setTextFormat('F');

        $excel_obj->create($lists, $header);
    }

    /**
     * @param $list
     * @param $fineGoodsInfo
     * @param array $joinResult
     * @return mixed
     */
    public function formatData($list,$fineGoodsInfo,$joinResult = [])
    {
        $uids = $list ? array_column($list, 'uid') : [];
        $userList = $uids ? User::getBatchBasicUserInfo($uids) : [];
        $userList = $userList ? array_column($userList, null, 'uid') : [];
        if (empty($joinResult)) {
            $recordIds = $list ? array_column($list, 'id') : [];
            $joinResult = $recordIds ? FineGoodsJoinModel::select('*',
                ['fine_goods_id' => $fineGoodsInfo['id'], 'record_id' => $recordIds]) : [];
        }
        $joinList = $joinResult ? array_column($joinResult, null, 'record_id') : [];
        $hasJoinedUsers = $uids ? FineGoodsJoinModel::all(['uid' => $uids, 'join_status' => FineGoodsJoinModel::JOIN_STATUS_PREFER, 'fine_goods_id[!]' => $fineGoodsInfo['id']], ['uid', 'fine_goods_id']) : [];
        $hasJoinedIds = $hasJoinedUsers ? array_column($hasJoinedUsers, 'fine_goods_id') : [];
        $hasJoinedActivityArr = $hasJoinedIds ? FineGoodsModel::all(['id' => $hasJoinedIds], ['id', 'activity_title']) : [];
        $hasJoinedActivityArr = $hasJoinedActivityArr ? array_column($hasJoinedActivityArr, null, 'id') : [];
        $userHasJoinedActivity = [];
        foreach ($hasJoinedUsers as $row) {
            if (isset($hasJoinedActivityArr[$row['fine_goods_id']])) {
                $userHasJoinedActivity[$row['uid']][] = $hasJoinedActivityArr[$row['fine_goods_id']]['activity_title'];
            }
        }
        //用户综合指数
        list($scoreMap, $tagList) = BigDataService::getScoreMap($uids);
        foreach ($list as &$row) {
            $row['join_status'] = FineGoodsJoinModel::JOIN_STATUS_NOT_DEFAULT;
            $row['logistics_status'] = 0;
            if (isset($joinList[$row['id']])) {
                $row['join_status'] = $joinList[$row['id']]['join_status'];
                $row['logistics_status'] = $joinList[$row['id']]['logistics_status'];
            }
            if (isset($userList[$row['uid']])) {
                $row['nick'] = $userList[$row['uid']]['nick'];
            }
            $row['activity_state'] = $fineGoodsInfo['activity_state'];
            $row['score'] = $scoreMap[$row['uid']];
            $row['tag_list'] = $tagList[$row['uid']]['tag'] ?? '';
            $row['history_title'] = isset($userHasJoinedActivity[$row['uid']]) ? $userHasJoinedActivity[$row['uid']] : [];
            $row['phone'] = PhoneModel::getExtendPhone($row['encrypt_phone_id'], UserExtendPhoneScene::GOODS_TEST_JOIN_PHONE);
        }
        return $list;
    }
}
